package com.yk.spark.util;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by YK on 2017/9/4.
 */
public class ExcelUtil {
    /**
     * 数据导出为excel
     * @param outputStream 输出流
     * @param valueMap  数据格式
     */
    public static void exportToExcel(BufferedOutputStream outputStream, Map<String, List<Integer>> valueMap){

        /*1.构建excel工作簿*/
        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("spark分析文件导出");

        for (Map.Entry<String, List<Integer>> entry: valueMap.entrySet()){
            Row row = sheet.createRow(sheet.getPhysicalNumberOfRows()); //创建一行

            Cell cell = row.createCell(row.getPhysicalNumberOfCells()); //创建单元格
            cell.setCellValue(entry.getKey());

            for (Integer in: entry.getValue()){
                cell = row.createCell(row.getPhysicalNumberOfCells());
                cell.setCellValue(in);
            }
        }
        /*2.开启输出流*/
        try {
            wb.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
